package com.lixixi.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

public class AliyunOSSutil {
	//获取环境变量,以便从环境变量中获取访问凭证
	final static private EnvironmentVariableCredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

	/** 生成唯一的一个文件名 */
	public static String generateUniqueBucketName(String fileName)
	{
		String uuidFileName = UUID.randomUUID().toString().replace("-", "") +
						fileName.substring(fileName.lastIndexOf("."));
		return uuidFileName;
	}

	/**
	 *
	 * @param endpoint 	地域节点
	 * @param bucketName 	Bucket名称
	 * @param region		Bucket地域
	 * @param multipartFile		上传文件
	 * @return
	 * @throws IOException
	 */
	public static Boolean upload(String endpoint, String bucketName, String region, MultipartFile multipartFile) throws IOException {
		//创建 OSSClient 实例
		ClientBuilderConfiguration clientBuilerConfiguration = new ClientBuilderConfiguration();
		//使用V4签名算法对 AccessKey 加密
		clientBuilerConfiguration.setSignatureVersion(SignVersion.V4);
		OSS ossClient = OSSClientBuilder.create()
						.endpoint(endpoint)
						.credentialsProvider(credentialsProvider)
						.region(region)
						.build();
		//获取 oss 输出流
		try
		{
			//创建PutobjectRequest实例
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, generateUniqueBucketName(multipartFile.getOriginalFilename()), new ByteArrayInputStream(multipartFile.getBytes()));
			// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
			// ObjectMetadata metadata = new ObjectMetadata();
			// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
			// metadata.setObjectAcl(CannedAccessControlList.Private);
			// putObjectRequest.setMetadata(metadata);

			//上传文件
			PutObjectResult result = ossClient.putObject(putObjectRequest);
		} catch (OSSException oe)
		{
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message:" + oe.getErrorMessage());
			System.out.println("Error Code:" + oe.getErrorCode());
			System.out.println("Request ID:" + oe.getRequestId());
			System.out.println("Host ID:" + oe.getHostId());
		}catch(ClientException ce){
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message:" + ce.getMessage());
		}finally
		{
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		//获取文件路径

		return true;
	}
}
